package com.mccken.springframework.beans.factory.support;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.mccken.springframework.beans.BeansException;
import com.mccken.springframework.beans.factory.config.BeanDefinition;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-11-28 18:58
 **/
public class SimpleInstantiationStrategy implements InstantiationStrategy{
	@Override
	public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) throws BeansException {

		Class clazz = beanDefinition.getBeanClass();
		try {
			if (constructor != null){
				return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
			} else {
				return clazz.getDeclaredConstructor().newInstance();
			}
		} catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException e) {
			throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e); 	
		}
	}
}
